package com.aaa.ssm.service.impl;

import com.aaa.ssm.dao.TuserDao;
import com.aaa.ssm.entity.Tuser;

import com.aaa.ssm.service.TuserService;
import com.aaa.ssm.util.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class TuserServiceImpl implements TuserService {
    @Resource
    private TuserDao tuserDao;
    @Override
    public Tuser checkUser(Tuser tuser) {
        Tuser tuserList = tuserDao.queryLogin(tuser);
        System.out.println("salt ===================================================================== " + tuserList);
        String oldPassword = tuser.getPassword();
        //获取盐值
        String salt = tuserList.getSalt();
        System.out.println("salt ===================================================================== " + salt);
        //生成加密密码
        Sha512Hash sha512Hash = new Sha512Hash(oldPassword,salt,1024);
        //比对加密过后的密码
        if (tuserList.getPassword().equals(sha512Hash.toString())){
            return tuserList;
        }
        return null;
    }
    private static String time(){
        //获取当前时间
        Date date = new Date();
        //实例化格式化时间类
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //format格式化时间
        String format = simpleDateFormat.format(date);
        return format;
    }
    @Override
    public PageInfo queryPage(Page<Tuser> page) {
        PageHelper.startPage(page.getPageNo(),page.getPageSize());
        return new PageInfo(tuserDao.queryByParam(page.getData()));
    }
    /**
     * 注册时判断手机号是否存在
     * @param mobile
     * @return
     */
    @Override
    public Tuser queryMobile(Tuser mobile) {
        Tuser tuser = tuserDao.queryMobile(mobile);
        return tuser;
    }

    @Override
    public int add(Tuser tuser) {
        String oldPassword = tuser.getPassword();
        //生成盐值
        String salt = UUID.randomUUID().toString();
        //生成加密密码
        Sha512Hash sha512Hash = new Sha512Hash(oldPassword,salt,1024);
        //设置加密过后的密码
        tuser.setPassword(sha512Hash.toString());
        //盐值
        tuser.setSalt(salt);
        tuser.setCjtime(time());
        return tuserDao.add(tuser);
    }

    /**
     * 更新
     * @param ptTuser
     * @return
     */
    @Override
    public int update(Tuser ptTuser) {
        ptTuser.setGxtime(time());
        return tuserDao.update(ptTuser);
    }
    @Override
    public int delete(int id) {
        return tuserDao.delete(id);
    }
}
